package com.yc.videosqllite.disk;

import com.yc.videosqllite.manager.CacheConfig;
import com.yc.videosqllite.manager.LocationManager;
import com.yc.videosqllite.model.SafeKeyGenerator;
import com.yc.videosqllite.model.VideoLocation;
import com.yc.videosqllite.utils.CacheLogUtils;

import java.io.File;

/**
 * 磁盘缓存工具
 *
 * @since 2021-05-10
 */
public class SqlLiteCache {
    /**
     * SafeKeyGenerator
     */
    public final SafeKeyGenerator safeKeyGenerator;
    private InterDiskCache interDiskCache;

    /**
     * SqlLiteCache
     */
    public SqlLiteCache() {
        CacheConfig cacheConfig = LocationManager.getInstance().getCacheConfig();
        File path = DiskFileUtils.getFilePath(cacheConfig.getContext());
        String pathString = path.getPath();
        CacheLogUtils.d("SqlLiteCache-----pathString路径输出地址-" + pathString);
        this.safeKeyGenerator = new SafeKeyGenerator();
        interDiskCache = DiskLruCacheWrapper.get(path, safeKeyGenerator);
    }

    /**
     * 存数据
     *
     * @param url 链接
     * @param location 视频数据
     */
    public synchronized void put(String url, VideoLocation location) {
        if (location == null) {
            return;
        }
        String safeKey = safeKeyGenerator.getSafeKey(url);
        location.setUrlMd5(safeKey);
        String json = location.toJson();
        CacheLogUtils.d("SqlLiteCache-----put--json--" + json);
        interDiskCache.put(url, json);
    }

    /**
     * 取数据
     *
     * @param url 链接
     * @return return
     */
    public synchronized long get(String url) {
        final int len = -1;
        String data = interDiskCache.get(url);
        if (data == null || data.length() == 0) {
            return len;
        }
        CacheLogUtils.d("SqlLiteCache-----get---" + data);
        VideoLocation location = VideoLocation.toObject(data);
        return location.getPosition();
    }

    /**
     * 移除数据
     *
     * @param url 链接
     * @return return
     */
    public synchronized boolean remove(String url) {
        return interDiskCache.remove(url);
    }

    /**
     * 是否包含
     *
     * @param url 链接
     * @return return
     */
    public synchronized boolean containsKey(String url) {
        return interDiskCache.containsKey(url);
    }

    /**
     * 清楚所有数据
     */
    public synchronized void clearAll() {
        interDiskCache.clear();
    }
}
